class MSSQLManager {
    constructor() {
        this.currentTable = null;
        this.currentPage = 1;
        this.pageSize = 50;
        this.totalRecords = 0;
        this.isConnected = false;
        this.init();
    }

    init() {
        this.bindEvents();
        this.showConnectionForm();
    }

    bindEvents() {
        // 连接表单提交
        document.getElementById('connectionForm').addEventListener('submit', (e) => {
            e.preventDefault();
            this.testConnection();
        });

        // 断开连接
        document.getElementById('disconnectBtn').addEventListener('click', () => {
            this.disconnect();
        });

        // 刷新表列表
        document.getElementById('refreshTablesBtn').addEventListener('click', () => {
            this.loadTables();
        });

        // 导出所有表
        document.getElementById('exportAllBtn').addEventListener('click', () => {
            this.exportAllTables();
        });

        // 分页按钮
        document.getElementById('prevPageBtn').addEventListener('click', () => {
            if (this.currentPage > 1) {
                this.currentPage--;
                this.loadTableData(this.currentTable);
            }
        });

        document.getElementById('nextPageBtn').addEventListener('click', () => {
            const totalPages = Math.ceil(this.totalRecords / this.pageSize);
            if (this.currentPage < totalPages) {
                this.currentPage++;
                this.loadTableData(this.currentTable);
            }
        });

        // 导出当前表
        document.getElementById('exportTableBtn').addEventListener('click', () => {
            if (this.currentTable) {
                this.exportTable(this.currentTable);
            }
        });

        // SQL查询相关
        document.getElementById('executeQueryBtn').addEventListener('click', () => {
            this.executeQuery();
        });

        document.getElementById('clearQueryBtn').addEventListener('click', () => {
            document.getElementById('sqlQuery').value = '';
            document.getElementById('queryResults').innerHTML = `
                <div class="text-center text-muted py-5">
                    <i class="bi bi-search display-4 mb-3"></i>
                    <p>执行SQL查询后，结果将显示在这里</p>
                </div>
            `;
            document.getElementById('exportQueryBtn').disabled = true;
        });

        document.getElementById('exportQueryBtn').addEventListener('click', () => {
            this.exportQueryResults();
        });
    }

    showConnectionForm() {
        document.querySelector('.connection-form').style.display = 'block';
        document.getElementById('tableContainer').style.display = 'none';
        document.getElementById('disconnectBtn').style.display = 'none';
        this.isConnected = false;
    }

    showTableContainer() {
        document.querySelector('.connection-form').style.display = 'none';
        document.getElementById('tableContainer').style.display = 'block';
        document.getElementById('disconnectBtn').style.display = 'inline-flex';
        this.isConnected = true;
        
        // 添加动画效果
        document.getElementById('tableContainer').classList.add('fade-in');
    }

    async testConnection() {
        const submitBtn = document.querySelector('#connectionForm button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        
        try {
            submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 连接中...';
            submitBtn.disabled = true;

            const formData = {
                server: document.getElementById('server').value,
                port: document.getElementById('port').value,
                database: document.getElementById('database').value,
                user: document.getElementById('user').value,
                password: document.getElementById('password').value
            };

            const response = await fetch('/api/test-connection', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            const result = await response.json();

            if (result.success) {
                this.showAlert('连接成功！', 'success');
                this.showManagementSection();
                this.loadTables();
            } else {
                this.showAlert('连接失败: ' + result.message, 'danger');
            }
        } catch (error) {
            this.showAlert('连接失败: ' + error.message, 'danger');
        } finally {
            submitBtn.innerHTML = originalText;
            submitBtn.disabled = false;
        }
    }

    async loadTables() {
        const tableList = document.getElementById('tableList');
        tableList.innerHTML = '<div class="loading"><div class="spinner-border spinner-border-sm" role="status"></div><span class="ms-2">加载中...</span></div>';

        try {
            const response = await fetch('/api/tables');
            const result = await response.json();

            if (result.success) {
                this.renderTableList(result.tables);
            } else {
                tableList.innerHTML = '<div class="alert alert-danger m-2">加载失败: ' + result.message + '</div>';
            }
        } catch (error) {
            tableList.innerHTML = '<div class="alert alert-danger m-2">加载失败: ' + error.message + '</div>';
        }
    }

    renderTableList(tables) {
        const tableList = document.getElementById('tableList');
        
        if (tables.length === 0) {
            tableList.innerHTML = '<div class="alert alert-info m-2">没有找到数据表</div>';
            return;
        }

        let html = '<div class="list-group list-group-flush">';
        tables.forEach(table => {
            html += `
                <a href="#" class="list-group-item list-group-item-action table-item" data-table="${table.TABLE_NAME}">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">${table.TABLE_NAME}</h6>
                        <small class="text-muted">${table.TABLE_SCHEMA}</small>
                    </div>
                </a>
            `;
        });
        html += '</div>';

        tableList.innerHTML = html;

        // 绑定表点击事件
        document.querySelectorAll('.table-item').forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                const tableName = item.dataset.table;
                this.selectTable(tableName);
            });
        });
    }

    selectTable(tableName) {
        // 更新选中状态
        document.querySelectorAll('.table-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-table="${tableName}"]`).classList.add('active');

        this.currentTable = tableName;
        this.currentPage = 1;
        document.getElementById('currentTableName').textContent = tableName;
        document.getElementById('tableInfoCard').style.display = 'block';

        // 1. 立即显示表结构（保持在结构标签页）
        this.loadTableStructure(tableName);
        
        // 2. 自动切换到数据浏览标签页并加载数据
        this.switchToDataTabAndLoad(tableName);
        
        // 3. 在SQL查询框中自动填充SELECT语句
        this.fillQueryWithSelect(tableName);
    }

    // 新增方法：切换到数据浏览标签页并加载数据
    switchToDataTabAndLoad(tableName) {
        // 使用Bootstrap的标签页API进行平滑切换
        const dataTabTrigger = new bootstrap.Tab(document.getElementById('data-tab'));
        
        // 添加切换动画效果
        setTimeout(() => {
            dataTabTrigger.show();
        }, 300); // 延迟300ms让表结构先加载
        
        // 加载表数据
        this.loadTableData(tableName);
        
        // 启用导出按钮
        document.getElementById('exportTableBtn').disabled = false;
        
        // 添加视觉提示
        this.showTabSwitchFeedback('数据浏览');
    }

    // 新增方法：在SQL查询框中填充SELECT语句
    fillQueryWithSelect(tableName) {
        const sqlQuery = document.getElementById('sqlQuery');
        const selectStatement = `SELECT * FROM ${tableName}`;
        sqlQuery.value = selectStatement;
        
        // 添加一个小的视觉提示，表明查询已自动填充
        sqlQuery.style.backgroundColor = '#e8f5e8';
        sqlQuery.style.transition = 'background-color 0.3s ease';
        setTimeout(() => {
            sqlQuery.style.backgroundColor = '';
        }, 1500);
        
        // 显示提示信息
        this.showAlert(`已自动填充查询语句: ${selectStatement}`, 'info');
    }

    // 新增方法：显示标签页切换反馈
    showTabSwitchFeedback(tabName) {
        const feedback = document.createElement('div');
        feedback.className = 'alert alert-info alert-dismissible fade show position-fixed';
        feedback.style.cssText = `
            top: 20px;
            right: 20px;
            z-index: 1050;
            min-width: 300px;
            animation: slideInRight 0.3s ease;
        `;
        feedback.innerHTML = `
            <i class="bi bi-info-circle me-2"></i>
            已自动切换到 <strong>${tabName}</strong> 标签页
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(feedback);
        
        // 3秒后自动消失
        setTimeout(() => {
            if (feedback.parentNode) {
                feedback.remove();
            }
        }, 3000);
    }

    async loadTableStructure(tableName) {
        const structureTable = document.getElementById('structureTable').getElementsByTagName('tbody')[0];
        structureTable.innerHTML = '<tr><td colspan="5" class="text-center">加载中...</td></tr>';

        try {
            const response = await fetch(`/api/table/${tableName}/structure`);
            const result = await response.json();

            if (result.success) {
                this.renderTableStructure(result.structure);
            } else {
                structureTable.innerHTML = '<tr><td colspan="5" class="text-center text-danger">加载失败: ' + result.message + '</td></tr>';
            }
        } catch (error) {
            structureTable.innerHTML = '<tr><td colspan="5" class="text-center text-danger">加载失败: ' + error.message + '</td></tr>';
        }
    }

    renderTableStructure(structure) {
        const tbody = document.getElementById('structureTable').getElementsByTagName('tbody')[0];
        tbody.innerHTML = '';

        if (!structure || structure.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" class="text-center text-muted py-4">
                        <i class="bi bi-exclamation-triangle display-4 mb-3 d-block"></i>
                        该表没有结构信息
                    </td>
                </tr>
            `;
            return;
        }

        structure.forEach((column, index) => {
            const row = tbody.insertRow();
            
            // 数据类型显示优化
            let dataTypeDisplay = column.DATA_TYPE.toUpperCase();
            if (column.CHARACTER_MAXIMUM_LENGTH) {
                dataTypeDisplay += `(${column.CHARACTER_MAXIMUM_LENGTH})`;
            } else if (column.NUMERIC_PRECISION && column.NUMERIC_SCALE !== null) {
                dataTypeDisplay += `(${column.NUMERIC_PRECISION},${column.NUMERIC_SCALE})`;
            } else if (column.NUMERIC_PRECISION) {
                dataTypeDisplay += `(${column.NUMERIC_PRECISION})`;
            }

            // 长度/精度显示优化
            let lengthPrecision = '-';
            if (column.CHARACTER_MAXIMUM_LENGTH) {
                lengthPrecision = `长度: ${column.CHARACTER_MAXIMUM_LENGTH}`;
            } else if (column.NUMERIC_PRECISION) {
                lengthPrecision = column.NUMERIC_SCALE !== null ? 
                    `精度: ${column.NUMERIC_PRECISION}, 小数位: ${column.NUMERIC_SCALE}` : 
                    `精度: ${column.NUMERIC_PRECISION}`;
            }

            // 默认值显示优化
            let defaultValue = column.COLUMN_DEFAULT || 'NULL';
            if (defaultValue !== 'NULL' && defaultValue.length > 30) {
                defaultValue = defaultValue.substring(0, 30) + '...';
            }

            row.innerHTML = `
                <td>
                    <div class="d-flex align-items-center">
                        <i class="bi bi-tag text-primary me-2"></i>
                        <strong>${column.COLUMN_NAME}</strong>
                        <small class="text-muted ms-2">#${index + 1}</small>
                    </div>
                </td>
                <td>
                    <span class="badge bg-secondary fs-6">${dataTypeDisplay}</span>
                </td>
                <td>
                    ${column.IS_NULLABLE === 'YES' ? 
                        '<span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>是</span>' : 
                        '<span class="badge bg-danger"><i class="bi bi-x-circle me-1"></i>否</span>'
                    }
                </td>
                <td>
                    <small class="text-muted">${lengthPrecision}</small>
                </td>
                <td>
                    <code class="small">${defaultValue}</code>
                </td>
            `;
        });

        // 添加表结构统计信息
        const statsRow = tbody.insertRow();
        statsRow.className = 'table-info';
        statsRow.innerHTML = `
            <td colspan="5" class="text-center py-2">
                <small class="text-muted">
                    <i class="bi bi-info-circle me-1"></i>
                    共 ${structure.length} 个字段
                </small>
            </td>
        `;
    }

    async loadTableData(tableName) {
        const tableDataDiv = document.getElementById('tableData');
        tableDataDiv.innerHTML = `
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">正在加载数据...</p>
            </div>
        `;

        try {
            const response = await fetch(`/api/table-data/${encodeURIComponent(tableName)}?page=${this.currentPage}&pageSize=${this.pageSize}`);
            const result = await response.json();

            if (result.success) {
                this.totalRecords = result.total;
                this.renderTableData(result.data, result.columns);
                this.updatePagination();
            } else {
                tableDataDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        加载数据失败: ${result.error}
                    </div>
                `;
            }
        } catch (error) {
            tableDataDiv.innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-wifi-off me-2"></i>
                    网络错误: ${error.message}
                </div>
            `;
        }
    }

    renderTableData(data, columns) {
        const tableDataDiv = document.getElementById('tableData');
        
        if (data.length === 0) {
            tableDataDiv.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="bi bi-inbox display-6 mb-2"></i>
                    <p>该表没有数据</p>
                </div>
            `;
            return;
        }

        const table = document.createElement('table');
        table.className = 'table table-hover data-table';
        
        // 创建表头
        const thead = document.createElement('thead');
        const headerRow = document.createElement('tr');
        columns.forEach(column => {
            const th = document.createElement('th');
            th.innerHTML = `<i class="bi bi-tag me-1"></i>${column}`;
            headerRow.appendChild(th);
        });
        thead.appendChild(headerRow);
        table.appendChild(thead);

        // 创建表体
        const tbody = document.createElement('tbody');
        data.forEach((row, index) => {
            const tr = document.createElement('tr');
            tr.style.animationDelay = `${index * 0.05}s`;
            tr.classList.add('slide-in');
            
            columns.forEach(column => {
                const td = document.createElement('td');
                const value = row[column];
                
                if (value === null || value === undefined) {
                    td.innerHTML = '<span class="text-muted fst-italic">NULL</span>';
                } else if (typeof value === 'boolean') {
                    td.innerHTML = value ? 
                        '<span class="badge bg-success">True</span>' : 
                        '<span class="badge bg-danger">False</span>';
                } else if (typeof value === 'number') {
                    td.innerHTML = `<code class="text-primary">${value}</code>`;
                } else if (value instanceof Date) {
                    td.innerHTML = `<small class="text-info">${value.toLocaleString()}</small>`;
                } else {
                    const strValue = String(value);
                    if (strValue.length > 50) {
                        td.innerHTML = `
                            <span title="${strValue}">${strValue.substring(0, 50)}...</span>
                        `;
                    } else {
                        td.textContent = strValue;
                    }
                }
                tr.appendChild(td);
            });
            tbody.appendChild(tr);
        });
        table.appendChild(tbody);

        tableDataDiv.innerHTML = '';
        tableDataDiv.appendChild(table);
    }

    updatePagination() {
        const totalPages = Math.ceil(this.totalRecords / this.pageSize);
        const paginationInfo = document.getElementById('paginationInfo');
        const prevBtn = document.getElementById('prevPageBtn');
        const nextBtn = document.getElementById('nextPageBtn');

        // 更新分页信息
        const startRecord = (this.currentPage - 1) * this.pageSize + 1;
        const endRecord = Math.min(this.currentPage * this.pageSize, this.totalRecords);
        
        paginationInfo.innerHTML = `
            <i class="bi bi-info-circle me-1"></i>
            显示 ${startRecord}-${endRecord} 条，共 ${this.totalRecords} 条记录 (第 ${this.currentPage}/${totalPages} 页)
        `;

        // 更新按钮状态
        prevBtn.disabled = this.currentPage <= 1;
        nextBtn.disabled = this.currentPage >= totalPages;
    }

    async exportTable() {
        if (!this.currentTable) {
            this.showAlert('请先选择一个表', 'warning');
            return;
        }

        const exportBtn = document.getElementById('exportBtn');
        const originalText = exportBtn.innerHTML;
        
        try {
            exportBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> 导出中...';
            exportBtn.disabled = true;

            const response = await fetch(`/api/table/${this.currentTable}/export`);
            
            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `${this.currentTable}.xlsx`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                this.showAlert('导出成功！', 'success');
            } else {
                const result = await response.json();
                this.showAlert('导出失败: ' + result.message, 'danger');
            }
        } catch (error) {
            this.showAlert('导出失败: ' + error.message, 'danger');
        } finally {
            exportBtn.innerHTML = originalText;
            exportBtn.disabled = false;
        }
    }

    async executeQuery() {
        const query = document.getElementById('sqlQuery').value.trim();
        if (!query) {
            this.showAlert('请输入SQL查询语句', 'warning');
            return;
        }

        const executeBtn = document.getElementById('executeQueryBtn');
        const originalText = executeBtn.innerHTML;
        executeBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> 执行中...';
        executeBtn.disabled = true;

        const queryResults = document.getElementById('queryResults');
        queryResults.innerHTML = `
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">执行中...</span>
                </div>
                <p class="mt-2">正在执行查询...</p>
            </div>
        `;

        try {
            const response = await fetch('/api/execute-query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ query })
            });

            const result = await response.json();

            if (result.success) {
                this.renderQueryResults(result.data, result.columns);
                document.getElementById('exportQueryBtn').disabled = false;
                
                // 显示查询成功信息
                const message = result.message || `查询执行成功，返回 ${result.data.length} 条记录`;
                this.showAlert(message, 'success');
            } else {
                queryResults.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        <strong>查询失败:</strong> ${result.error}
                    </div>
                `;
                document.getElementById('exportQueryBtn').disabled = true;
            }
        } catch (error) {
            queryResults.innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-wifi-off me-2"></i>
                    <strong>网络错误:</strong> ${error.message}
                </div>
            `;
            document.getElementById('exportQueryBtn').disabled = true;
        } finally {
            executeBtn.innerHTML = originalText;
            executeBtn.disabled = false;
        }
    }

    renderQueryResults(data, columns) {
        const queryResults = document.getElementById('queryResults');
        
        if (!data || data.length === 0) {
            queryResults.innerHTML = `
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>
                    查询执行成功，但没有返回数据
                </div>
            `;
            return;
        }

        const table = document.createElement('table');
        table.className = 'table table-hover data-table';
        
        // 创建表头
        const thead = document.createElement('thead');
        const headerRow = document.createElement('tr');
        columns.forEach(column => {
            const th = document.createElement('th');
            th.innerHTML = `<i class="bi bi-tag me-1"></i>${column}`;
            headerRow.appendChild(th);
        });
        thead.appendChild(headerRow);
        table.appendChild(thead);

        // 创建表体
        const tbody = document.createElement('tbody');
        data.forEach((row, index) => {
            const tr = document.createElement('tr');
            tr.style.animationDelay = `${index * 0.05}s`;
            tr.classList.add('slide-in');
            
            columns.forEach(column => {
                const td = document.createElement('td');
                const value = row[column];
                
                if (value === null || value === undefined) {
                    td.innerHTML = '<span class="text-muted fst-italic">NULL</span>';
                } else if (typeof value === 'boolean') {
                    td.innerHTML = value ? 
                        '<span class="badge bg-success">True</span>' : 
                        '<span class="badge bg-danger">False</span>';
                } else if (typeof value === 'number') {
                    td.innerHTML = `<code class="text-primary">${value}</code>`;
                } else if (value instanceof Date) {
                    td.innerHTML = `<small class="text-info">${value.toLocaleString()}</small>`;
                } else {
                    const strValue = String(value);
                    if (strValue.length > 50) {
                        td.innerHTML = `
                            <span title="${strValue}">${strValue.substring(0, 50)}...</span>
                        `;
                    } else {
                        td.textContent = strValue;
                    }
                }
                tr.appendChild(td);
            });
            tbody.appendChild(tr);
        });
        table.appendChild(tbody);

        // 添加结果统计
        const resultInfo = document.createElement('div');
        resultInfo.className = 'alert alert-success mb-3';
        resultInfo.innerHTML = `
            <i class="bi bi-check-circle me-2"></i>
            查询成功返回 <strong>${data.length}</strong> 条记录
        `;

        queryResults.innerHTML = '';
        queryResults.appendChild(resultInfo);
        queryResults.appendChild(table);
    }

    showManagementSection() {
        this.showTableContainer();
    }

    disconnect() {
        this.showConnectionForm();
        
        // 清空表单和数据
        document.getElementById('connectionForm').reset();
        document.getElementById('sqlQuery').value = '';
        document.getElementById('queryResults').innerHTML = `
            <div class="text-center text-muted py-5">
                <i class="bi bi-search display-4 mb-3"></i>
                <p>执行SQL查询后，结果将显示在这里</p>
            </div>
        `;
        document.getElementById('exportQueryBtn').disabled = true;
        
        this.currentTable = null;
        this.currentPage = 1;
        this.totalRecords = 0;
    }

    showAlert(message, type) {
        // 移除现有的alert
        const existingAlert = document.querySelector('.alert-dismissible');
        if (existingAlert) {
            existingAlert.remove();
        }

        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
        alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        alertDiv.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        document.body.appendChild(alertDiv);

        // 3秒后自动消失
        setTimeout(() => {
            if (alertDiv.parentNode) {
                alertDiv.remove();
            }
        }, 3000);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new MSSQLManager();
});